package cn.lanqiao.jdbc;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public abstract class BaseDao<T> {
    String driver = "com.mysql.cj.jdbc.Driver";
    String url = "jdbc:mysql://localhost:3306/sxu";
    String user = "root";
    String password = "123";

    Class<T> clazz;

    //反射获得clazz
    public BaseDao() {
        clazz = (Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    /**
     * 建立连接
     */
    protected Connection createConnection() {
        Connection conn = null;
        try {
            //1. 注册驱动 (仅仅做一次)
            Class.forName(driver);
            //2. 建立连接(Connection)
            conn = DriverManager.getConnection(url, user, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 关闭连接
     */
    protected void closeAll(ResultSet resultSet, Statement statement, Connection connection) {
        //6. 释放资源
        try {
            if (resultSet != null)
                resultSet.close();
            if (statement != null)
                statement.close();
            if (connection != null)
                connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭连接
     */
    protected void closeAll(Statement statement, Connection connection) {
        //6. 释放资源
        try {
            if (statement != null)
                statement.close();
            if (connection != null)
                connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 字符串拼接SQL语句
     *
     * @param sql
     * @return 影响条数
     */
    public int executeUpdate(String sql) {
        Connection conn = null;
        Statement statement = null;
        int ret = -1;
        try {
            conn = createConnection();
            //3. 创建运行SQL的语句(Statement)
            statement = conn.createStatement();
            //4. 运行语句
            ret = statement.executeUpdate(sql);
            //5. 处理运行结果(ResultSet) DML不需要此步骤
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //6. 释放资源
            closeAll(statement, conn);
        }
        return ret;
    }

    /**
     * 预编译SQL语句
     *
     * @param sql
     * @param objects
     * @return 影响条数
     */
    public int executeUpdate(String sql, Object... objects) {
        Connection conn = null;
        PreparedStatement statement = null;
        int ret = -1;
        try {
            conn = createConnection();
            //3. 创建运行SQL的语句(Statement)
            statement = conn.prepareStatement(sql);
            for (int i = 0; i < objects.length; i++) {
                statement.setObject(i + 1, objects[i]);
            }
            //4. 运行语句
            ret = statement.executeUpdate();
            //5. 处理运行结果(ResultSet) DML不需要此步骤
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //6. 释放资源
            closeAll(statement, conn);
        }
        return ret;
    }


    public List<T> executeQuery(String sql, Object... objects) {
        ResultSet rs = null;
        List<T> list = new ArrayList<>();
        Connection conn = null;
        PreparedStatement statement = null;
        try {
            conn = createConnection();
            //3. 创建运行SQL的语句(Statement)
            statement = conn.prepareStatement(sql);
            for (int i = 0; i < objects.length; i++) {
                statement.setObject(i + 1, objects[i]);
            }
            //4. 运行语句
            rs = statement.executeQuery();
            //5. 处理运行结果(ResultSet) DML不需要此步骤
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();
            while (rs.next()) {
                //实例化对象 eg: User user = new User();
                T t = clazz.getConstructor().newInstance();
                //ORM ：列和属性 -> 获得列名 -> 得到属性名
                for (int i = 0; i < columnCount; i++) {
                    // 如果名字一样，正常取出，否则会报错
                    Field f = null;
                    try {
                        f = clazz.getDeclaredField(rsmd.getColumnLabel(i + 1));
                    } catch (NoSuchFieldException e) {
                        //列名和属性名不一致，读取注解，获得对应名字。
                        Field[] declaredFields = clazz.getDeclaredFields();
                        for (Field declaredField : declaredFields) {
                            ColumnNameMapper annotation = declaredField.getAnnotation(ColumnNameMapper.class);
                            if (annotation != null) {
                                if (annotation.value().equals(rsmd.getColumnLabel(i + 1)))
                                    f = clazz.getDeclaredField(declaredField.getName());
                            }
                        }
                    }
                    f.setAccessible(true);
                    f.set(t, rs.getObject(i + 1));
                }
                //其他属性赋值略
                list.add(t);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //6. 释放资源
            closeAll(statement, conn);
        }
        return list;
    }

}
